package com.patent.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.patent.common.CreateOrderNum;
import com.patent.common.DateUtil;
import com.patent.common.HttpClientUtils;
import com.patent.common.JsonUtil;
import com.patent.common.NumberUtil;
import com.patent.common.PatentConstant;
import com.patent.common.ResultCode;
import com.patent.common.ResultData;
import com.patent.dao.MonitorPatentMapper;
import com.patent.dao.OverdueFineMapper;
import com.patent.dao.PatentAgentFeeMapper;
import com.patent.dao.PatentMapper;
import com.patent.dao.PatentOrderMapper;
import com.patent.dao.PaymentRecordMapper;
import com.patent.dao.UnpaidFeeMapper;
import com.patent.domain.po.MonitorPatent;
import com.patent.domain.po.Patent;
import com.patent.domain.po.PatentAgentFee;
import com.patent.domain.po.PatentOrder;
import com.patent.domain.po.PaymentRecord;
import com.patent.domain.po.UnpaidFee;
import com.patent.domain.vo.IndexInfoVo;
import com.patent.domain.vo.PatentCountVo;
import com.patent.domain.vo.PatentFeeVo;
import com.patent.domain.vo.PatentOrderVo;
import com.patent.domain.vo.PaymentAndPatentVo;
import com.patent.service.PatentService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("patentService")
@Transactional
public class PatentServiceImpl implements PatentService {

	private static final Logger log = LoggerFactory.getLogger(PatentServiceImpl.class);

	@Resource(name="patentMapper")
	private PatentMapper patentMapper;

	@Resource(name="monitorPatentMapper")
	private MonitorPatentMapper monitorPatentMapper;

	@Resource(name="unpaidFeeMapper")
	private UnpaidFeeMapper unpaidFeeMapper;

	@Resource(name="patentAgentFeeMapper")
	private PatentAgentFeeMapper patentAgentFeeMapper;

	@Resource(name="paymentRecordMapper")
	private PaymentRecordMapper paymentRecordMapper;

	@Resource(name="patentOrderMapper")
	private PatentOrderMapper patentOrderMapper;

	@Resource(name="overdueFineMapper")
	private OverdueFineMapper overdueFineMapper;

	@Override
	public PageInfo<Patent> getPatentInfoByConditions(String userMobile, String applicationNo, String title, String applicants, String inventors,
	                                              Integer page, Integer rows, String flag) throws Exception{
		PageInfo<Patent> pageInfo = null;
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("applicationNo",applicationNo);
		map.put("title",title);
		map.put("applicants",applicants);
		map.put("inventors",inventors);
		map.put("userMobile",userMobile);
		/*map.put("page",(page-1)*rows);
		map.put("rows",rows);*/
		if(StringUtils.isNotBlank(flag) && "1".equals(flag)){
			page = 1;
			rows = 100000;
			PageHelper.startPage(page, rows);
			List<Patent> list = patentMapper.getPatentInfoByConditions(map);
			if(list != null && list.size() > 0){
				List<MonitorPatent> monitorPatentList = new ArrayList<MonitorPatent>();
				for(int i=0; i<list.size(); i++){
					MonitorPatent monitorPatent = new MonitorPatent();
					monitorPatent.setPatentId(list.get(i).getId());
					//monitorPatent.setSource(source);
					monitorPatent.setUserMobile(userMobile);
					monitorPatent.setValidFlag(PatentConstant.YES_FLAG);
					monitorPatentList.add(monitorPatent);
				}
				monitorPatentMapper.addMonitorPatentList(monitorPatentList);
			}
			pageInfo = null;
		}else{
			PageHelper.startPage(page, rows);
			List<Patent> list = patentMapper.getPatentInfoByConditions(map);
			pageInfo = new PageInfo<Patent>(list);
		}
		return pageInfo;
	}

	@Override
	public ResultData addMonitorPatent(String source, String userMobile, String id) {
		ResultData resultData = new ResultData();
		String ids[] = id.split(",");
		//判断是否有专利已经被监控
		/*boolean flag = false;
		String repeatPatentId = "";
		for(int i=0;i<ids.length;i++){
			int count = monitorPatentMapper.selectByPatentId(Integer.parseInt(ids[i]));
			if(count != 0){
				flag = true;
				repeatPatentId = ids[i];
				break;
			}
		}
		if(flag){
			resultData.setCode(ResultCode.repeatError.getCode());
			resultData.setMsg("专利号："+repeatPatentId+"已被添加监控，请勿重复添加");
			return resultData;
		}*/
		List<MonitorPatent> monitorPatentList = new ArrayList<MonitorPatent>();
		for(int i=0;i<ids.length;i++){
			MonitorPatent monitorPatent = new MonitorPatent();
			monitorPatent.setPatentId(Integer.parseInt(ids[i]));
			monitorPatent.setSource(source);
			monitorPatent.setUserMobile(userMobile);
			monitorPatent.setValidFlag(PatentConstant.YES_FLAG);
			monitorPatentList.add(monitorPatent);
		}
		try {
			//批量添加监控专利
			monitorPatentMapper.addMonitorPatentList(monitorPatentList);
			resultData.setCode(ResultCode.success.getCode());
			resultData.setMsg(ResultCode.success.getMessage());
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return resultData;
	}

	@Override
	public ResultData queryIndexCount(String userMobile) throws Exception {
		ResultData resultData = new ResultData();
		//查年费监控数量
		Map<String,Object> annualMap = new HashMap<String,Object>();
		annualMap.put("userMobile",userMobile);
		List<String> caseStatuList = new ArrayList<String>();
		caseStatuList.add("专利权维持");
		caseStatuList.add("待公告");
		caseStatuList.add("无效宣告失效");
		caseStatuList.add("未缴年费专利权终止，等恢复");
		caseStatuList.add("等年费滞纳金");
		caseStatuList.add("等待颁证公告");
		annualMap.put("caseStatuList",caseStatuList);
		IndexInfoVo indexInfoVo = monitorPatentMapper.queryIndexPatentCount(annualMap);
		//查专利数量
		Integer monitorPatentCount = monitorPatentMapper.selectCountByUserMobile(userMobile);
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("indexInfoVo",indexInfoVo);
		resultMap.put("monitorPatentCount",monitorPatentCount);
		resultData.setCode(ResultCode.success.getCode());
		resultData.setMsg(ResultCode.success.getMessage());
		resultData.setResult(resultMap);
		return resultData;
	}

	@Override
	public ResultData queryMonitorPatentInfo(String userMobile, String patentType, String generalStatus,Integer page,Integer rows) {
		ResultData resultData = new ResultData();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userMobile",userMobile);
		patentType = transformPatentType(patentType);
		map.put("patentType",patentType);
		if(StringUtils.isNotBlank(generalStatus)){
			if(PatentConstant.authorizedFlag.equals(generalStatus)){
				generalStatus = "有效";
			}else if(PatentConstant.failureFlag.equals(generalStatus)){
				generalStatus = "无效";
			}else if(PatentConstant.applicationFlag.equals(generalStatus)){
				generalStatus = "审中";
			}
		}
		List<PatentCountVo> patentCountVoList = new ArrayList<PatentCountVo>();
		if(StringUtils.isBlank(patentType)){
			for(int i=1;i<= 3;i++){
				if(i == 1 ){
					map.put("patentType","发明");
				}else if(i == 2 ){
					map.put("patentType","实用新型");
				}else if(i == 3 ){
					map.put("patentType","外观设计");
				}
				List<PatentCountVo> pc1 = monitorPatentMapper.queryMonitorPatentCount(map);
				PatentCountVo patentCountVo = new PatentCountVo();
				if(pc1 != null && pc1.size() > 0){
					patentCountVo = pc1.get(0);
					String patentType1 = patentCountVo.getPatentType();
					if("发明专利".equals(patentType1)){
						patentCountVo.setPatentTypeId(PatentConstant.inventFlag);
					}else if("实用新型".equals(patentType1)){
						patentCountVo.setPatentTypeId(PatentConstant.newTypeFlag);
					}else if("外观设计".equals(patentType1)){
						patentCountVo.setPatentTypeId(PatentConstant.facadeFlag);
					}
				}else{
					if(i ==1 ){
						patentCountVo.setPatentTypeId(PatentConstant.inventFlag);
						patentCountVo.setPatentType("发明专利");
					}
					if(i ==2 ){
						patentCountVo.setPatentTypeId(PatentConstant.newTypeFlag);
						patentCountVo.setPatentType("实用新型");
					}
					if(i ==3 ){
						patentCountVo.setPatentTypeId(PatentConstant.facadeFlag);
						patentCountVo.setPatentType("外观设计");
					}
					patentCountVo.setPatentTypeCount(0);
					patentCountVo.setApplicationCount(0);
					patentCountVo.setAuthorizedCount(0);
					patentCountVo.setFailureCount(0);
				}
				patentCountVoList.add(patentCountVo);
			}
		}else{
			patentCountVoList = monitorPatentMapper.queryMonitorPatentCount(map);
			if(patentCountVoList == null || patentCountVoList.size() == 0){
				PatentCountVo patentCountVo = new PatentCountVo();
				if("发明".equals(patentType)){
					patentCountVo.setPatentTypeId(PatentConstant.inventFlag);
					patentCountVo.setPatentType("发明专利");
				}else if("实用新型".equals(patentType)){
					patentCountVo.setPatentTypeId(PatentConstant.newTypeFlag);
					patentCountVo.setPatentType("实用新型");
				}else if("外观设计".equals(patentType)){
					patentCountVo.setPatentTypeId(PatentConstant.facadeFlag);
					patentCountVo.setPatentType("外观设计");
				}
				patentCountVo.setPatentTypeCount(0);
				patentCountVo.setApplicationCount(0);
				patentCountVo.setAuthorizedCount(0);
				patentCountVo.setFailureCount(0);
				patentCountVoList.add(patentCountVo);
			}

		}

		//如果patentType有值的话，查被监控的专利信息,默认是申请中的专利信息（generalStatus无值）
		map.put("generalStatus",generalStatus);
		Map<String,Object> resultMap = new HashMap<String,Object>();
		if(StringUtils.isBlank(patentType)){//专利类型为空，查各个专利数量
			resultMap.put("patentCountVoList",patentCountVoList);
		}else{
			if(patentCountVoList != null && patentCountVoList.size() > 0){
				map.put("page",(page-1)*rows);
				map.put("rows",rows);
				List<Patent> patentList = monitorPatentMapper.queryMonitorPatentInfo(map);
				resultMap.put("patentInfoList",patentList);
				resultMap.put("patentCount",patentCountVoList.get(0));
			}
		}
		resultData.setCode(ResultCode.success.getCode());
		resultData.setMsg(ResultCode.success.getMessage());
		resultData.setResult(resultMap);
		return resultData;
	}

	@Override
	public ResultData queryAnnualFee(String userMobile,String patentType,Integer page,Integer rows, String applicationNo) {
		ResultData resultData = new ResultData();
		Map<String,Object> map11 = new HashMap<String,Object>();
		map11.put("userMobile",userMobile);
		List<String> caseStatuList = new ArrayList<String>();
		caseStatuList.add("专利权维持");
		caseStatuList.add("待公告");
		caseStatuList.add("无效宣告失效");
		caseStatuList.add("未缴年费专利权终止，等恢复");
		caseStatuList.add("等年费滞纳金");
		caseStatuList.add("等待颁证公告");
		map11.put("caseStatuList",caseStatuList);
		if(StringUtils.isNotBlank(applicationNo)){
			map11.put("applicationNo",applicationNo);
		}
		IndexInfoVo indexInfoVo = monitorPatentMapper.queryIndexPatentCount(map11);
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("indexInfoVo",indexInfoVo);  //各个专利数量
		Map<String,Object> queryMap = new HashMap<String,Object>();
		queryMap.put("userMobile",userMobile);
		patentType = transformPatentType(patentType);
		queryMap.put("patentType",patentType);
		queryMap.put("page",(page-1)*rows);
		queryMap.put("rows",rows);
		queryMap.put("caseStatuList",caseStatuList);
		if(StringUtils.isNotBlank(applicationNo)){
			queryMap.put("applicationNo",applicationNo);
		}
		//查询所有的监控id
		List<PatentFeeVo> monList = unpaidFeeMapper.selectAllIds(queryMap);
		List<PatentFeeVo> patentFeeVoList = new ArrayList<>();
		if(!monList.isEmpty()) {
			patentFeeVoList = unpaidFeeMapper.queryPatentFee(monList);
			if (patentFeeVoList != null && patentFeeVoList.size() > 0) {
				for (int i = 0; i < patentFeeVoList.size(); i++) {
					PatentFeeVo patentFeeVo = patentFeeVoList.get(i);
					List<UnpaidFee> ufList = patentFeeVo.getUfList();
					if (ufList != null && ufList.size() > 0) {
						patentFeeVo.setPatentId(ufList.get(0).getPatentId());
						patentFeeVo.setAmount(ufList.get(0).getAmount());
						patentFeeVo.setDueDate(ufList.get(0).getDueDate());
						patentFeeVo.setType(ufList.get(0).getType());
					}
					patentFeeVo.setUfList(null);
					Integer patentId = patentFeeVo.getPatentId();
					String newPatentType = patentFeeVo.getPatentType();
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("patentId", patentId);
					PaymentRecord record = paymentRecordMapper.selectRecordByPatentId(patentId);  //查支付成功的最近一条记录
					if (record != null) {
						String newType = record.getType();
						Integer year = NumberUtil.getNumFromString(newType);
						map.put("type", "第" + (year + 1));
						if ((newPatentType.contains("发明") && (year + 1) > 20) || (newPatentType.contains("实用新型") && (year + 1) > 10) ||
						    (newPatentType.contains("外观设计") && (year + 1) > 10)) {
							//最后一年已交完
							//patentFeeVoList.remove(i);
							patentFeeVoList.get(i).setShowFlag("0");
						} else {
							UnpaidFee unpaidFee = unpaidFeeMapper.queryUnpaidFee(map);
							if (unpaidFee != null) {
								patentFeeVo.setType(unpaidFee.getType());
								patentFeeVo.setDueDate(unpaidFee.getDueDate());
								patentFeeVo.setAmount(unpaidFee.getAmount());
							}
						}
					}
				}
			}
			//滞纳金、代理费（都100）、恢复权利费用(数据库查)
			BigDecimal needFee = new BigDecimal(0);  //总费用
			if(patentFeeVoList != null && patentFeeVoList.size() >0){
				for(int j = 0; j < patentFeeVoList.size(); j++){
					PatentFeeVo patentFeeVo = patentFeeVoList.get(j);
					Integer amount = patentFeeVo.getAmount();
					//代理费
					patentFeeVo.setAgentFee(new BigDecimal(100));
					needFee = new BigDecimal(amount).add(new BigDecimal(100));
					patentFeeVo.setNeedFee(needFee);
					//算滞纳金和恢复专利的费用
					String caseStatus = patentFeeVo.getCaseStatus();
					Integer patentId = patentFeeVo.getPatentId();
					Date dueDate = patentFeeVo.getDueDate();
					String type = patentFeeVo.getType();
					String filingStr = patentFeeVo.getFilingDate();  //申请日
					patentType = patentFeeVo.getPatentType();
					Integer year = NumberUtil.getNumFromString(type); //专利年限
					BigDecimal overDueFee = new BigDecimal(0);
					if(StringUtils.isNotBlank(caseStatus)){
						if("未缴年费专利权终止，等恢复".equals(caseStatus)){
							//根据专利号查滞纳金总额和恢复专利权费用
							List<UnpaidFee> unpaidFees = unpaidFeeMapper.selectListByPatentId(patentId);
							long time = 0;
							if(unpaidFees != null && unpaidFees.size() > 0){
								for(int i = 0;i<unpaidFees.size();i++){
									String utype = unpaidFees.get(i).getType();
									if(StringUtils.isNotBlank(utype) && utype.contains("年费滞纳金")){
										time = unpaidFees.get(i).getDueDate().getTime();
									}
									if(StringUtils.isNotBlank(utype) && utype.contains("恢复权利请求费")){
										patentFeeVo.setDueDate(unpaidFees.get(i).getDueDate());
									}
									if(dueDate != null && time == dueDate.getTime()){//需交滞纳金和恢复权利费用
										overDueFee = overDueFee.add(new BigDecimal(unpaidFees.get(i).getAmount()));
										patentFeeVo.setOverDueFee(overDueFee);
									}else{
										break;
									}
								}
								needFee = needFee.add(overDueFee);
								if(patentFeeVo.getOverDueFee() != null){
									patentFeeVo.setRestoreFee(new BigDecimal(1000));
									patentFeeVo.setOverDueFee(patentFeeVo.getOverDueFee().subtract(new BigDecimal(1000)));
								}
							}
						}else {//数据库可能没爬到，自己算(等年费滞纳金或者其他)
							//查代理费(固定100，不用查库)
							Map<String, Object> agentMap = new HashMap<String, Object>();
							agentMap.put("year", year);
							agentMap.put("patentType", patentType);
							PatentAgentFee patentAgentFee = patentAgentFeeMapper.queryAgentFee(agentMap);
							//算滞纳金
							if (StringUtils.isNotBlank(filingStr)) {
								Date newDate = DateUtil.getNewDate(filingStr, year);
								Date date = new Date();
								Integer i = date.compareTo(newDate);
								if (i > 0) {
									int dueMonth = DateUtil.getMonthDiff(date, newDate) + 1;
									if (dueMonth > 8) { //不能再进行专利缴费 TODO:超过8个月的也显示
										//patentFeeVo.setShowFlag("0");
										patentFeeVo.setDueDate(DateUtil.getNewDate(newDate, 8));
									} else {
										patentFeeVo.setDueDate(DateUtil.getNewDate(newDate, dueMonth));
									}
									Long patentFee = patentAgentFee.getPatentFee();  //全年代理费
									Map<String, BigDecimal> map = getOverDueFee(patentFee, dueMonth); //滞纳金
									patentFeeVo.setOverDueFee(new BigDecimal(map.get("overDueFee").intValue()));
									patentFeeVo.setRestoreFee(new BigDecimal(map.get("restoreFee").intValue()));
									needFee = needFee.add(patentFeeVo.getOverDueFee()).add(patentFeeVo.getRestoreFee());
									patentFeeVo.setNeedFee(needFee);
								}
							}

							/*List<OverdueFine> overdueFines = overdueFineMapper.selectListByPatentId(patentId);
							if(overdueFines != null && overdueFines.size() > 0){
								String overDueDate = overdueFines.get(overdueFines.size() - 1).getDueDate();  //2018年09月04日到2018年10月08日
								long time = parseDueDateString(overDueDate);
								if(dueDate != null && time == dueDate.getTime()){ //需交滞纳金
									//判断需交多少滞纳金并修改展示的截止日期
									long nowTime = DateUtil.getNowDate().getTime();
									if(nowTime > dueDate.getTime()){//滞纳金在最后一档(超过最后一档的加1000)
										overDueFee = new BigDecimal(overdueFines.get(overdueFines.size() - 1).getFineAmount()).add(new BigDecimal(1000));
										patentFeeVo.setOverDueFee(overDueFee);
									}else{//滞纳金在中间档
										for(int i = 0; i < overdueFines.size(); i++){
											long timei = parseDueDateString(overdueFines.get(i).getDueDate());
											if(timei < nowTime){
												continue;
											}else{
												overDueFee = new BigDecimal(overdueFines.get(i).getFineAmount());
												patentFeeVo.setDueDate(new Date(timei));
												patentFeeVo.setOverDueFee(overDueFee);
												break;
											}
										}
									}
									needFee = needFee.add(overDueFee);
								}
							}*/
							}
							patentFeeVo.setNeedFee(needFee);
					}

					if(StringUtils.isNotBlank(filingStr)) {
						Date newDate = DateUtil.getNewDate(filingStr, year);
						Date date = DateUtil.getNowDate();
						Integer i = date.compareTo(newDate);
						Integer dMonth = 0;
						if(i < 0){
							dMonth = DateUtil.getMonthDiff(newDate, date);
						}
						patentFeeVo.setDiffMonth(dMonth);
					}
				}
			}

			//判断是否需要交滞纳金(自己算)
			/*BigDecimal needFee = new BigDecimal(0);  //总费用
			if (patentFeeVoList != null && patentFeeVoList.size() > 0) {
				for (int j = 0; j < patentFeeVoList.size(); j++) {
					PatentFeeVo patentFeeVo = patentFeeVoList.get(j);
					Integer amount = patentFeeVo.getAmount();
					patentFeeVo.setAgentFee(new BigDecimal(100));
					needFee = new BigDecimal(amount).add(new BigDecimal(100));
					patentFeeVo.setNeedFee(needFee);
					String type = patentFeeVo.getType();
					patentType = patentFeeVo.getPatentType();
					Integer year = NumberUtil.getNumFromString(type); //专利年限
					//查代理费(固定100，不用查库)
					Map<String, Object> agentMap = new HashMap<String, Object>();
					agentMap.put("year", year);
					agentMap.put("patentType", patentType);
					PatentAgentFee patentAgentFee = patentAgentFeeMapper.queryAgentFee(agentMap);
					//算滞纳金
					Date date = new Date();
					String filingStr = patentFeeVo.getFilingDate();  //申请日
					if (StringUtils.isNotBlank(filingStr)) {
						Date newDate = DateUtil.getNewDate(filingStr, year);
						patentFeeVo.setDueDate(newDate);
						Integer i = date.compareTo(newDate);
						Integer dMonth = 0;
						if (i > 0) {
							int dueMonth = DateUtil.getMonthDiff(date, newDate) + 1;
							if (dueMonth > 8) { //不能再进行专利缴费
								patentFeeVo.setShowFlag("0");
							} else {
								Long patentFee = patentAgentFee.getPatentFee();  //全年代理费
								Map<String, BigDecimal> map = getOverDueFee(patentFee, dueMonth); //滞纳金
								patentFeeVo.setOverDueFee(new BigDecimal(map.get("overDueFee").intValue()));
								patentFeeVo.setRestoreFee(new BigDecimal(map.get("restoreFee").intValue()));
								needFee = needFee.add(patentFeeVo.getOverDueFee()).add(patentFeeVo.getRestoreFee());
								patentFeeVo.setNeedFee(needFee);
							}
						} else {
							dMonth = DateUtil.getMonthDiff(newDate, date);
						}
						patentFeeVo.setDiffMonth(dMonth);
					}
				}
			}*/

		}
		resultMap.put("patentFeeVoList",patentFeeVoList);
		resultData.setResult(resultMap);
		resultData.setCode(ResultCode.success.getCode());
		resultData.setMsg(ResultCode.success.getMessage());
		return resultData;

	}

	@Override
	public ResultData cancelMonitorPatent(String monitorId) throws Exception{
		ResultData resultData = new ResultData();
		MonitorPatent monitorPatent = new MonitorPatent();
		monitorPatent.setId(Integer.parseInt(monitorId));
		monitorPatent.setValidFlag(0);
		monitorPatent.setUpdateDate(new Date());
		monitorPatentMapper.updateByPrimaryKeySelective(monitorPatent);
		resultData.setCode(ResultCode.success.getCode());
		resultData.setMsg(ResultCode.success.getMessage());
		return resultData;
	}

	@Override
	public ResultData savePaymentRecord(String userMobile, List<PatentOrderVo> list) {
		ResultData resultData = new ResultData();
		//查专利对应的年费信息，代理费用，滞纳金
		BigDecimal allFee = new BigDecimal(0);  //多个总费用
		StringBuffer stringBuffer = new StringBuffer();
		Integer size = list.size();
		for(PatentOrderVo orderVo : list){
			PaymentRecord paymentRecord = new PaymentRecord();
			BigDecimal needFee = new BigDecimal(0);  //单个总费用
			Integer patentId = orderVo.getPatentId();
			String type = orderVo.getType();
			Integer patentYear = NumberUtil.getNumFromString(type);  //年
			String patentType = type.substring(0,4); //专利类型
			Map<String, Object> agentMap = new HashMap<String, Object>();
			agentMap.put("patentType", patentType);
			agentMap.put("year", patentYear);
			PatentAgentFee patentAgentFee = patentAgentFeeMapper.queryAgentFee(agentMap);
			//算滞纳金
			Patent patent = patentMapper.selectByPrimaryKey(patentId);
			Date date = DateUtil.getNowDate();
			if(patent != null){
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("type", type);
				map.put("patentId", patent.getId());
				UnpaidFee unpaidFee = unpaidFeeMapper.queryUnpaidFee(map);
				Long patentFee = unpaidFee.getAmount().longValue();
				Date dueDate = unpaidFee.getDueDate();
				Long agentFee = 100l;
				//代理费优惠计算
				if(size > 1 && size < 5){
					//agentFee = new BigDecimal(agentFee).multiply(new BigDecimal(0.8)).longValue();
					agentFee = 80l;
				}else if(size >= 5 && size < 10 ){
					//agentFee = new BigDecimal(agentFee).multiply(new BigDecimal(0.8))
						//.multiply(new BigDecimal(0.8)).longValue();
					agentFee = 64l;
				}else if(size >= 10){
					/*agentFee = new BigDecimal(agentFee).multiply(new BigDecimal(0.8))
						.multiply(new BigDecimal(0.6)).longValue();*/
					agentFee = 48l;
				}

				Integer overDueFee = 0;
				if(StringUtils.isNotBlank(patent.getFilingDate())){
					String caseStatus = patent.getCaseStatus();
					if(StringUtils.isNotBlank(caseStatus)){
						if("未缴年费专利权终止，等恢复".equals(caseStatus)){
							List<UnpaidFee> unpaidFees = unpaidFeeMapper.selectListByPatentId(patentId);
							long time = 0;
							if(unpaidFees != null && unpaidFees.size() > 0){
								for(int i = 0;i<unpaidFees.size();i++){
									String typeV = unpaidFees.get(i).getType();
									if(StringUtils.isNotBlank(typeV) && typeV.contains("年费滞纳金")){
										time = unpaidFees.get(i).getDueDate().getTime();
									}
									if(dueDate != null && time == dueDate.getTime()){//需交滞纳金和恢复权利费用
										overDueFee += unpaidFees.get(i).getAmount();
									}else{
										break;
									}
								}
							}
						}else {//自己算（等年费滞纳金或者其他状态的）
							Date newDate = DateUtil.getNewDate(patent.getFilingDate(), patentYear);
							Integer i = date.compareTo(newDate);
							if(i > 0) {
								int dueMonth = DateUtil.getMonthDiff(date, newDate) + 1;
								if (dueMonth > 0) {
									Map<String, BigDecimal> dueMap = getOverDueFee(patentAgentFee.getPatentFee(), dueMonth); //滞纳金
									overDueFee = new BigDecimal(dueMap.get("overDueFee").intValue()).add(new BigDecimal(dueMap.get("restoreFee").intValue())).intValue();
								}
							}else if(i < 0 && size == 1 ){//提前交的
								int dMonth = DateUtil.getMonthDiff(newDate, date);
								if(dMonth >= 1){//单件提前一个月交的8折
									//agentFee = new BigDecimal(agentFee).multiply(new BigDecimal(0.8)).longValue();
									agentFee = 80l;
								}
							}
							/*List<OverdueFine> overdueFines = overdueFineMapper.selectListByPatentId(patentId);
							if(overdueFines != null && overdueFines.size() > 0){
								String overDueDate = overdueFines.get(overdueFines.size() - 1).getDueDate();  //2018年09月04日到2018年10月08日
								long time = parseDueDateString(overDueDate);
								if(dueDate != null && time == dueDate.getTime()){ //需交滞纳金
									//判断需交多少滞纳金并修改展示的截止日期
									long nowTime = DateUtil.getNowDate().getTime();
									if(nowTime > dueDate.getTime()){//滞纳金在最后一档(多交1000)
										overDueFee = overdueFines.get(overdueFines.size() - 1).getFineAmount() + 1000;
									}else{//滞纳金在中间档
										for(int i = 0; i < overdueFines.size(); i++){
											long timei = parseDueDateString(overdueFines.get(i).getDueDate());
											if(timei < nowTime){
												continue;
											}else{
												overDueFee = overdueFines.get(i).getFineAmount();
												break;
											}
										}
									}
								}
							}*/
						}
					}
				}

				/*if(StringUtils.isNotBlank(patent.getFilingDate())){
					Date newDate = DateUtil.getNewDate(patent.getFilingDate(), patentYear);
					Integer i = date.compareTo(newDate);
					if(i < 0 && size == 1 ){//提前交的
						int dMonth = DateUtil.getMonthDiff(newDate, date);
						if(dMonth >= 1){//单件提前一个月交的8折
							//agentFee = new BigDecimal(agentFee).multiply(new BigDecimal(0.8)).longValue();
							agentFee = 80l;
						}
					}
				}
				Integer overDueFee = 0;
				String caseStatus = patent.getCaseStatus();
				if(StringUtils.isNotBlank(caseStatus)){
					if("等年费滞纳金".equals(caseStatus)){
						List<OverdueFine> overdueFines = overdueFineMapper.selectListByPatentId(patentId);
						if(overdueFines != null && overdueFines.size() > 0){
							String overDueDate = overdueFines.get(overdueFines.size() - 1).getDueDate();  //2018年09月04日到2018年10月08日
							long time = parseDueDateString(overDueDate);
							if(dueDate != null && time == dueDate.getTime()){ //需交滞纳金
								//判断需交多少滞纳金并修改展示的截止日期
								long nowTime = DateUtil.getNowDate().getTime();
								if(nowTime > dueDate.getTime()){//滞纳金在最后一档(多交1000)
									overDueFee = overdueFines.get(overdueFines.size() - 1).getFineAmount() + 1000;
								}else{//滞纳金在中间档
									for(int i = 0; i < overdueFines.size(); i++){
										long timei = parseDueDateString(overdueFines.get(i).getDueDate());
										if(timei < nowTime){
											continue;
										}else{
											overDueFee = overdueFines.get(i).getFineAmount();
											break;
										}
									}
								}
							}
						}
					}else if("未缴年费专利权终止，等恢复".equals(caseStatus)){
						List<UnpaidFee> unpaidFees = unpaidFeeMapper.selectListByPatentId(patentId);
						long time = 0;
						if(unpaidFees != null && unpaidFees.size() > 0){
							for(int i = 0;i<unpaidFees.size();i++){
								String typeV = unpaidFees.get(i).getType();
								if(StringUtils.isNotBlank(typeV) && typeV.contains("年费滞纳金")){
									time = unpaidFees.get(i).getDueDate().getTime();
								}
								if(dueDate != null && time == dueDate.getTime()){//需交滞纳金和恢复权利费用
									overDueFee += unpaidFees.get(i).getAmount();
								}else{
									break;
								}
							}
						}
					}
				}*/

				paymentRecord.setUserMobile(userMobile);
				paymentRecord.setPatentId(patentId);
				paymentRecord.setType(type);
				needFee = needFee.add(new BigDecimal(patentFee)).add(new BigDecimal(agentFee)).add(new BigDecimal(overDueFee));
				paymentRecord.setPaymentAmount(needFee);
				paymentRecord.setOfficialAmount(patentFee.doubleValue());
				paymentRecord.setAgentAmount(agentFee.doubleValue());
				paymentRecord.setCreateDate(new Date());
				paymentRecord.setValidFlag(PatentConstant.YES_FLAG);
				paymentRecord.setOrderState(PatentConstant.NO_PAY);
				paymentRecord.setOrderNo(PatentConstant.PATENT_ORDER_FLAG + CreateOrderNum.getOrderNo());
				paymentRecordMapper.insertSelective(paymentRecord);
				allFee = allFee.add(needFee);
				stringBuffer.append(String.valueOf(paymentRecord.getId()).concat(","));
			}
		}
		try {
			//保存一个总的订单
			PatentOrder patentOrder = new PatentOrder();
			patentOrder.setUserMobile(userMobile);
			patentOrder.setOrderNo(PatentConstant.ALL_PATENT_ORDER_FLAG + CreateOrderNum.getOrderNo());
			patentOrder.setCreateDate(new Date());
			patentOrder.setValidFlag(PatentConstant.YES_FLAG);
			patentOrder.setOrderState(PatentConstant.NO_PAY);
			patentOrder.setPayAmount(allFee.doubleValue());
			patentOrder.setPaymentRecordId(stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1 ));
			patentOrderMapper.insert(patentOrder);
			resultData.setCode(ResultCode.success.getCode());
			resultData.setMsg(ResultCode.success.getMessage());
			resultData.setResult(patentOrder.getOrderNo());
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error("保存专利缴费信息失败："+e.getMessage());
		}
		return resultData;
	}

	@Override
	public ResultData queryPaymentRecord(String userMobile,Integer page,Integer rows) {
		ResultData resultData = new ResultData();
		Map<String,Object> queryMap = new HashMap<String,Object>();
		queryMap.put("userMobile",userMobile);
		queryMap.put("page",(page-1)*rows);
		queryMap.put("rows",rows);
		List<PaymentAndPatentVo> list =  paymentRecordMapper.queryPaymentRecord(queryMap);
		resultData.setCode(ResultCode.success.getCode());
		resultData.setMsg(ResultCode.success.getMessage());
		resultData.setResult(list);
		return resultData;
	}

	@Override
	public ResultData queryPatentInfo(String userMobile, String applicationNo) {
		ResultData resultData = new ResultData();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("userMobile", userMobile);
		map.put("applicationNo", applicationNo);
		List<MonitorPatent> list = monitorPatentMapper.selectByMap(map);
		if(list == null || list.size() == 0){
			resultData.setCode(ResultCode.dataNotMatchCode.getCode());
			resultData.setMsg(ResultCode.dataNotMatchCode.getMessage());
			return resultData;
		}
		Patent patent = patentMapper.queryPatentInfoByApplicationNo(applicationNo);
		if(patent == null){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("未查到此专利号相关的信息");
		}else{
			resultData.setCode(ResultCode.success.getCode());
			resultData.setMsg(ResultCode.success.getMessage());
			resultData.setResult(patent);
		}
		return resultData;
	}

	@Override
	public ResultData checkPatentStatu(String userMobile, String applicationNo) {
		ResultData resultData = new ResultData();
		Patent patent = patentMapper.queryPatentInfoByApplicationNo(applicationNo);
		Boolean flag = true;
		if(patent == null){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("未查到此专利号相关的信息");
		}else{
			String caseStatus = patent.getCaseStatus();

			if(StringUtils.isNotBlank(caseStatus)&&"专利权维持".equals(caseStatus)){
				resultData.setResult(flag);
			}else{
				flag = false;
				resultData.setResult(flag);
			}
			resultData.setCode(ResultCode.success.getCode());
			resultData.setMsg(ResultCode.success.getMessage());
		}
		return resultData;
	}

	/**
	 * 手动添加专利监控
	 */
	@Override
	public ResultData addPatentByManual(String source, String userMobile, String applicationNo) {
		ResultData resultData = new ResultData();
		//添加专利到patent
		String url = "http://api.shineip.com/patents";  //东泽提供
		Map map = new HashMap();
		map.put("application_no", applicationNo);
		try {
			String str = HttpClientUtils.doPost(url, null,map);
			log.info("插入专利表数据返回：" + str);
			Map<String, Object> resultMap = JsonUtil.json2Map(str);
			Integer code = (Integer) resultMap.get("code");
			Integer status = (Integer) resultMap.get("status");
			/*if(!PatentConstant.SUCCESS_CODE.equals(code)){
				resultData.setCode(ResultCode.otherError.getCode());
				resultData.setMsg(ResultCode.otherError.getMessage());
				return resultData;
			}*/
			if(PatentConstant.EXIST_STATUS.equals(status)){//已存在
				resultData.setCode(ResultCode.repeatError.getCode());
				resultData.setMsg(ResultCode.repeatError.getMessage());
				return resultData;
			}
			if(PatentConstant.ERROR_STATUS.equals(status)){//专利号验证不通过
				resultData.setCode(ResultCode.paramError.getCode());
				resultData.setMsg(ResultCode.paramError.getMessage());
				return resultData;
			}
			/*if(PatentConstant.SUCCESS_CODE.equals(code) && PatentConstant.SUCCESS_STATUS.equals(status)){//验证通过并保存成功*/
				//专利号查专利主键
			Patent patent = patentMapper.queryPatentInfoByApplicationNo(applicationNo);
			log.info("addPatentByManual patent：" + JsonUtil.write2JsonStr(patent));
			if(patent != null){
				Integer id = patent.getId();
				ResultData addResult = addMonitorPatent(source, userMobile, String.valueOf(id));
				if(addResult != null && ResultCode.success.getCode().equals(addResult.getCode())){
					resultData.setCode(ResultCode.success.getCode());
					resultData.setMsg(ResultCode.success.getMessage());
				}else{
					throw new RuntimeException("手动添加专利数据插入失败");
				}
			}
			/*}*/
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error("系统异常："+e.getMessage());
		}
		//添加监控到监控表
		return resultData;
	}

	@Override
	public List<Patent> getPatentInfoByConditions2(String applicationNo, String title,
	                                                   String applicants, String inventors, Integer page,
	                                                   Integer rows) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("applicationNo",applicationNo);
		map.put("title",title);
		map.put("applicants",applicants);
		map.put("inventors",inventors);
		map.put("page",(page-1)*rows);
		map.put("rows",rows);
		List<Patent> list = patentMapper.getPatentInfoByConditions2(map);
		return list;
	}

	/**
	 * 转换patentType
	 */
	private String transformPatentType(String patentType){
		if(StringUtils.isNotBlank(patentType)){
			if(PatentConstant.inventFlag.equals(patentType)){
				patentType = "发明";
			}else if(PatentConstant.newTypeFlag.equals(patentType)){
				patentType = "实用新型";
			}else if(PatentConstant.facadeFlag.equals(patentType)){
				patentType = "外观设计";
			}
		}else{
			patentType = "";
		}
		return patentType;
	}

	/**
	 * 算滞纳金
	 * @param patentFee  全年代理费
	 * @param dueMonth   超过的月数
	 * @return
	 */
	private Map<String, BigDecimal> getOverDueFee(Long patentFee,int dueMonth){
		Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
		BigDecimal overDueFee = new BigDecimal(0);
		BigDecimal restoreFee = new BigDecimal(0);
		if(dueMonth > 1 && dueMonth <= 6){ //超过截止日期六个月之内只算滞纳金，第一个月不交滞纳金
			overDueFee = new BigDecimal(patentFee).multiply(new BigDecimal(0.05)).multiply(new BigDecimal(dueMonth-1));
		}else if(dueMonth > 6){ //超过6个月后还有两个月期限
			overDueFee = (new BigDecimal(patentFee).multiply(new BigDecimal(0.05)).multiply(new BigDecimal(5)));
			restoreFee = new BigDecimal(1000);
		}
		map.put("overDueFee", overDueFee);
		map.put("restoreFee", restoreFee);
		return map;
	}

	private Long parseDueDateString(String dueDate){
		long time = 0;
		if(StringUtils.isNotBlank(dueDate)){
			StringBuffer stringBuffer = new StringBuffer();
			stringBuffer.append(dueDate.substring(12,16));
			stringBuffer.append("-");
			stringBuffer.append(dueDate.substring(17,19));
			stringBuffer.append("-");
			stringBuffer.append(dueDate.substring(20,22));
			time = DateUtil.formatStringToDate(stringBuffer.toString(),new SimpleDateFormat("yyyy-MM-dd")).getTime();
		}
		return time;
	}

}
